package com.example.demofdfs.test2;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.junit.Test;
import org.springframework.lang.Nullable;
import org.springframework.util.SerializationUtils;

import com.example.demofdfs.test.obj.Singleton;

public class SingletonTest {

	@Test
	public void test() {
		System.out.println(Singleton.instance());
		System.out.println(Singleton.instance());
		System.out.println(Singleton.instance());
		System.out.println(Singleton.instance());
	}
	
	@Test
	public void test2() {
		Thread t1 = new SingleObjThread();
		Thread t2 = new SingleObjThread();
		Thread t3 = new SingleObjThread();
		
		t1.start();
		t2.start();
		t3.start();
		System.out.println(Singleton.instance());
		System.out.println(Singleton.instance());
		System.out.println(Singleton.instance());
	}
	
	@Test
	public void test3() {
		Object o = Singleton.instance();
		System.out.println(o);
		byte[] b = serialize(o);
		Object o2 = deserialize(b);
		System.out.println("deserialize : " + o2);
	}
	
	@Test
	public void test4() {
		Object o = Singleton.instance();
		System.out.println(o);
		Class<?> clazz = o.getClass();
		Object o2;
		try {
			Constructor<?> c = clazz.getDeclaredConstructor();
			c.setAccessible(true);
			o2 = c.newInstance();
			System.out.println(o2);
		} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		System.out.println(Singleton.instance());
	}
	
	private static class SingleObjThread extends Thread {

		@Override
		public void run() {
			System.out.println(Singleton.instance());
		}
		
	}
	
	/*--------------------- serialize util ----------------------*/
	public static byte[] serialize(@Nullable Object object) {
		if (object == null) {
			return null;
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
		try {
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			oos.flush();
		}
		catch (IOException ex) {
			throw new IllegalArgumentException("Failed to serialize object of type: " + object.getClass(), ex);
		}
		return baos.toByteArray();
	}
	
	public static Object deserialize(@Nullable byte[] bytes) {
		if (bytes == null) {
			return null;
		}
		try {
			ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
			return ois.readObject();
		}
		catch (IOException ex) {
			throw new IllegalArgumentException("Failed to deserialize object", ex);
		}
		catch (ClassNotFoundException ex) {
			throw new IllegalStateException("Failed to deserialize object type", ex);
		}
	}
}
